document.addEventListener('DOMContentLoaded', init);

async function init() {
  // 加载现有的URL映射
  await loadMappings();
  
  // 添加映射按钮事件
  document.getElementById('addMapping').addEventListener('click', addMapping);
}

// 加载并显示URL映射
async function loadMappings() {
  const mappingsContainer = document.getElementById('mappingsContainer');
  mappingsContainer.innerHTML = '加载中...';
  
  try {
    const data = await browser.storage.local.get('urlMappings');
    const mappings = data.urlMappings || {};
    
    if (Object.keys(mappings).length === 0) {
      mappingsContainer.innerHTML = `<div class="empty-state">暂无URL映射。请添加第一条映射。</div>`;
      return;
    }
    
    let html = '';
    for (const [original, target] of Object.entries(mappings)) {
      html += `
        <div class="mapping-item" data-original="${escapeHtml(original)}">
          <div class="mapping-text">
            <span class="mapping-icon">⇒</span>
            <span class="mapping-original" title="${escapeHtml(original)}">${truncate(original, 40)}</span>
            <br>
            <span class="mapping-target" title="${escapeHtml(target)}">→ ${truncate(target, 45)}</span>
          </div>
          <div class="actions">
            <button class="edit-btn" title="编辑">✎</button>
            <button class="delete-btn" title="删除">✕</button>
          </div>
        </div>
      `;
    }
    
    mappingsContainer.innerHTML = html;
    
    // 添加删除按钮事件
    document.querySelectorAll('.delete-btn').forEach(btn => {
      btn.addEventListener('click', deleteMapping);
    });
    
    // 添加编辑按钮事件
    document.querySelectorAll('.edit-btn').forEach(btn => {
      btn.addEventListener('click', editMapping);
    });
    
  } catch (e) {
    console.error('加载URL映射失败:', e);
    mappingsContainer.innerHTML = `<div class="error">加载失败: ${e.message}</div>`;
  }
}

// 添加新的URL映射
async function addMapping() {
  const originalInput = document.getElementById('originalUrl');
  const targetInput = document.getElementById('targetUrl');
  
  const original = originalInput.value.trim();
  const target = targetInput.value.trim();
  
  if (!original || !target) {
    alert('请输入原始URL和目标URL');
    return;
  }
  
  try {
    // 测试正则表达式是否有效
    new RegExp(original);
  } catch (e) {
    alert(`无效的正则表达式: ${e.message}`);
    return;
  }
  
  try {
    const data = await browser.storage.local.get('urlMappings');
    const mappings = data.urlMappings || {};
    
    mappings[original] = target;
    
    await browser.storage.local.set({ urlMappings: mappings });
    
    originalInput.value = '';
    targetInput.value = '';
    
    await loadMappings();
  } catch (e) {
    console.error('添加映射失败:', e);
    alert(`保存失败: ${e.message}`);
  }
}

// 删除URL映射
async function deleteMapping(e) {
  const item = e.target.closest('.mapping-item');
  const original = item.dataset.original;
  try {
    const data = await browser.storage.local.get('urlMappings');
    const mappings = data.urlMappings || {};
    
    delete mappings[original];
    
    await browser.storage.local.set({ urlMappings: mappings });
    await loadMappings();
  } catch (e) {
    console.error('删除映射失败:', e);
    alert(`删除失败: ${e.message}`);
  }
}

// 编辑URL映射
async function editMapping(e) {
  const item = e.target.closest('.mapping-item');
  const original = item.dataset.original;
  
  const data = await browser.storage.local.get('urlMappings');
  const mappings = data.urlMappings || {};
  const target = mappings[original];
  
  document.getElementById('originalUrl').value = original;
  document.getElementById('targetUrl').value = target;
  
  // 删除旧映射
  delete mappings[original];
  await browser.storage.local.set({ urlMappings: mappings });
  
  await loadMappings();
}

// 工具函数 - 转义HTML
function escapeHtml(unsafe) {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

// 工具函数 - 截断文本
function truncate(text, maxLength) {
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength - 3) + '...';
}